//
//  ViewController.m
//  图片折叠效果
//
//  Created by YaosuMac on 2020/6/16.
//  Copyright © 2020 YaosuMac. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *topView;
@property (weak, nonatomic) IBOutlet UIImageView *bottomView;
@property (weak, nonatomic) IBOutlet UIView *drawView;
@property (nonatomic,strong) CAGradientLayer *gradientL;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //设置contentsRect可以设置图片显示的尺寸，取值0~1
    self.topView.layer.contentsRect = CGRectMake(0, 0, 1, 0.5);
    //设置锚点
    self.topView.layer.anchorPoint = CGPointMake(0.5, 1);
    
    self.bottomView.layer.contentsRect = CGRectMake(0, 0.5, 1, 0.5);
    self.bottomView.layer.anchorPoint = CGPointMake(0.5, 0);
    
    //添加手势
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(pan:)];
    [self.drawView addGestureRecognizer:pan];
    
    //渐变图层
    _gradientL = [CAGradientLayer layer];
    
    //注意图层需要设置尺寸
    _gradientL.frame = self.bottomView.bounds;
    //设置图层的透明度
    _gradientL.opacity = 0;
    //设置图层的颜色数组
    _gradientL.colors = @[(id)UIColor.clearColor.CGColor,(id)UIColor.blackColor.CGColor];
    
//    gradientL.colors = @[(id)UIColor.redColor.CGColor,(id)UIColor.blueColor.CGColor,(id)UIColor.greenColor.CGColor];
//
//    gradientL.locations = @[@0.4,@0.5,@0.3];
//
//    //设置起点
//    gradientL.startPoint = CGPointMake(0, 1);
    
    [self.bottomView.layer addSublayer:_gradientL];
}

-(void)pan:(UIPanGestureRecognizer *)pan
{
    //获取偏移量
    CGPoint transP = [pan translationInView:self.drawView];
    
    //旋转角度，往下逆时针旋转
    CGFloat angle = -transP.y / 128.0 * M_PI;
    CATransform3D transform = CATransform3DMakeRotation(angle, 1, 0, 0);
    
    //增加旋转的立体感，近大远小，d：距离土城的距离
    transform.m34 = -1 / 500.0;
    transform = CATransform3DRotate(transform, angle, 1, 0, 0);
    
    self.topView.layer.transform = transform;
    
    //设置阴影效果
    _gradientL.opacity = transP.y * 1/128;
    
    if (pan.state == UIGestureRecognizerStateEnded) {//反弹
        //弹簧效果的动画
        //SpringWithDamping 弹性系数，越小，弹簧效果越明显
        //SpringVelocity 弹簧初始速度
        [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.3 initialSpringVelocity:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            
            self.topView.layer.transform = CATransform3DIdentity;
            
            self.gradientL.opacity = 0;
            
        } completion:^(BOOL finished) {
            
        }];
    }
    
    NSLog(@"%s",__func__);
}


@end
